﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using StoryTimeline.Models;
using StoryTimeline.ViewModels;
using System.Data.Entity.Infrastructure;

namespace StoryTimeline.Controllers
{
    public class FactController : Controller
    {
        private StoryTimelineEntities db = new StoryTimelineEntities();

        // GET: /Fact/
        public ActionResult Index()
        {
            return View(db.Facts.ToList());
        }

        // GET: /Fact/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Fact fact = db.Facts.Find(id);
            if (fact == null)
            {
                return HttpNotFound();
            }
            return View(fact);
        }

        // GET: /Fact/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Fact/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="Text,Date,Rate")] Fact fact)
        {
            if (ModelState.IsValid)
            {
                db.Facts.Add(fact);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(fact);
        }

        // GET: /Fact/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var fact = db.Facts
                .Include(f => f.Stories).Single(f => f.Id == id);
            PopulateStoryFactsData(fact);

            if (fact == null)
            {
                return HttpNotFound();
            }
            return View(fact);
        }

        private void PopulateStoryFactsData(Fact fact)
        {
            var allStories = db.Stories;
            var factStories = new HashSet<int>(fact.Stories.Select(sf => sf.Id));
            var viewModel = allStories.Select(story => new StoryFactData
            {
                Assigned = factStories.Contains(story.Id),
                StoryID = story.Id,
                Title = story.Name
            }).ToList();
            ViewBag.Stories = viewModel;
        }

        // POST: /Fact/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult Edit([Bind(Include="Id,Text,Date,Rate")] Fact fact)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.Entry(fact).State = EntityState.Modified;
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }
        //    return View(fact);
        //}


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int? id, string[] selectedStories)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var factToUpdate = db.Facts.Include(f => f.Stories).Single(f => f.Id == id);
            if (TryUpdateModel(factToUpdate, "", new string[] {"Text", "Date", "Rate", "StoryFacts"}))
            {
                try
                {
                    UpdateFactStories(selectedStories, factToUpdate);

                    db.Entry(factToUpdate).State = EntityState.Modified;
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
                catch (RetryLimitExceededException)
                {
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }
            PopulateStoryFactsData(factToUpdate);
            return View(factToUpdate);
        }

        private void UpdateFactStories(string[] selectedStories, Fact factToUpdate)
        {
            if (selectedStories == null)
            {
                factToUpdate.Stories = new List<Story>();
                return;
            }

            var selectedStoriesHS = new HashSet<string>(selectedStories);
            var factStories = new HashSet<int>(factToUpdate.Stories.Select(sf => sf.Id));
            foreach (var story in db.Stories)
            {
                if (selectedStoriesHS.Contains(story.Id.ToString()))
                {
                    if (!factStories.Contains(story.Id))
                    {
                        factToUpdate.Stories.Add(story);
                    }
                    
                }
                else
                {
                    if (factStories.Contains(story.Id))
                    {
                        factToUpdate.Stories.Remove(story);
                    }
                }
            }
        }

        // GET: /Fact/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Fact fact = db.Facts.Find(id);
            if (fact == null)
            {
                return HttpNotFound();
            }
            return View(fact);
        }

        // POST: /Fact/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Fact fact = db.Facts.Find(id);
            db.Facts.Remove(fact);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
